package com.sljy.hzk.ui.exam;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.sljy.hzk.R;
import com.sljy.hzk.animation.AnimationManager;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.ExamErrDetailEntity;
import com.sljy.hzk.entity.ExamInfosEntity;
import com.sljy.hzk.entity.ExamMainEntity;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.ExamService;
import com.sljy.hzk.ui.QrCodeActivity;
import com.sljy.hzk.ui.fragment.ExamHistoryFragment;
import com.sljy.hzk.ui.fragment.ExamPlanFragment;
import com.sljy.hzk.util.TimeUtils;
import com.sljy.hzk.view.adapter.ExamNoticeAdapter;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.tencent.bugly.crashreport.crash.c.l;

@ActivityInfo(layout = R.layout.activity_exam_loading, isShowActionBar = true,title = "培训考试",rightIcRes = R.drawable.homepage)
public class ExamLoadingActivity extends BaseActivity {
    @BindView(R.id.curBtn)
    ToggleButton curBtn;
    @BindView(R.id.lastBtn)
    ToggleButton lastBtn;
    @BindView(R.id.nextBtn)
    ToggleButton nextBtn;
    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.qrBtn)
    ImageButton qrBtn;
    @BindView(R.id.priceBtn)
    ImageButton priceBtn;
    @BindView(R.id.historyBtn)
    ImageButton historyBtn;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    UserEntity user;
    ExamNoticeAdapter adapter;
    private ExamMainEntity examMainEntity;
    private int curState = 0;
    @Override
    protected void init() {
        user = UserInfo.getUserInfo();
        initTime();
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                refresh.setRefreshing(false);
                onRefreshToast();
                adapter.refresh(curState);
            }
        });
        HttpHeper.get().create(ExamService.class)
                .getAllExam(user.getCpId(), user.getPId())
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.newThread())
                //进行分组,插入头部,今天明天后天需要单独处理
                .map(data -> {
//                    List<Integer> pos = new ArrayList<>();
//                    List<ExamMainEntity.HisRecordsBean> hisRecordsBeanList = data.getData().getHisRecords();
//                    List<ExamMainEntity.ExamListBean> examListBeanList = data.getData().getExamList();
//                    if (hisRecordsBeanList != null && hisRecordsBeanList.size() != 0) {
//                        pos.add(0);
//                        for (int i = 0; i < hisRecordsBeanList.size(); i++) {
//                            if (i != 0 && i != hisRecordsBeanList.size()) {
//                                if (!TimeUtils.isOnemMonth(hisRecordsBeanList.get(i).getDate(), hisRecordsBeanList.get(i - 1).getDate())) {
//                                    pos.add(i);
//                                }
//                            }
//                        }
//                        for (int i = 0; i < pos.size(); i++) {
//                            hisRecordsBeanList.add(pos.get(i) + i, new ExamMainEntity.HisRecordsBean("-1"));
//                        }
//                        data.getData().setHisRecords(hisRecordsBeanList);
//                    }
//                    //今天明天后天
//                    pos.clear();
//                    pos.add(0);
//                    if (examListBeanList != null && examListBeanList.size() != 0) {
//                        for (int i = 0; i < examListBeanList.size(); i++) {
//                            if (i != 0 && i != examListBeanList.size()) {
//                                if (!examListBeanList.get(i).getDate().equals(examListBeanList.get(i - 1).getDate())) {
//                                    pos.add(i);
//                                }
//                            }
//                        }
//                        for (int i = 0; i < pos.size(); i++) {
//                            examListBeanList.add(pos.get(i) + i, new ExamMainEntity.ExamListBean("-1"));
//                        }
//                        data.getData().setExamList(examListBeanList);
//                    }
                    return data;
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseCallBack<ExamMainEntity>(this){
                    @Override
                    public void onCallBackSuccess(ExamMainEntity data) {
                        //examMainEntity = new ExamMainEntity();
                        examMainEntity = data;
                        curBtn.setChecked(true);
                    }
                    @Override
                    public void onFail(String mes) {
                        showToast(mes);
                    }
                });

        priceBtn.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(DoEffect(v,event)){
                    startActivity(ExamPriceActivity.class);
                }
                return false;
            }
        });

        historyBtn.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(DoEffect(v,event)){
                    startActivity(ExamMainActivity.class);
                }
                return false;
            }
        });

    }

    /**
     * 显示时间
     * */
    private void initTime(){
        //设置文本
        Date c = TimeUtils.getNowDate();
        curBtn.setTextOn(stringToU(TimeUtils.dateToStr(c)));
        curBtn.setTextOff(stringToU(TimeUtils.dateToStr(c)));
        lastBtn.setTextOn(stringToU(TimeUtils.dateToStr(TimeUtils.getBeforeDay(c))));
        lastBtn.setTextOff(stringToU(TimeUtils.dateToStr(TimeUtils.getBeforeDay(c))));
        nextBtn.setTextOn(stringToU(TimeUtils.dateToStr(TimeUtils.getTomorrowDay(c))));
        nextBtn.setTextOff(stringToU(TimeUtils.dateToStr(TimeUtils.getTomorrowDay(c))));
        //禁用没有通知得按钮
    }


    /**
     * 转换样式
     * */
    private String stringToU(String str){
        String s = str.substring(0,4);
        String s2 = str.substring(5,10);
        str = s+"\n"+s2;
        return str.replace("-",".");
    }


    /**
     * 今天
     * */
    @OnCheckedChanged({R.id.curBtn})
    public void OnCurTimeBtnClick(CompoundButton buttonView, boolean isChecked){
        if(isChecked){
            curBtn.setEnabled(false);
            lastBtn.setEnabled(true);
            nextBtn.setEnabled(true);
            lastBtn.setChecked(false);
            nextBtn.setChecked(false);
            if(adapter == null){
                adapter= new ExamNoticeAdapter(examMainEntity.getExamList(),ExamLoadingActivity.this);
                listView.setAdapter(adapter);
            }else
                adapter.refresh(0);
            curState = 0;
        }
    }
    /**
     * 上一天
     * */
    @OnCheckedChanged({R.id.lastBtn})
    public void OnLastTimeBtnClick(CompoundButton buttonView, boolean isChecked){
        if(isChecked){
            lastBtn.setEnabled(false);
            curBtn.setEnabled(true);
            nextBtn.setEnabled(true);
            curBtn.setChecked(false);
            nextBtn.setChecked(false);
            if(adapter != null)
                adapter.refresh(1);
            curState = 1;
        }
    }
    /**
     * 下一天
     * */
    @OnCheckedChanged({R.id.nextBtn})
    public void OnNextTimeBtnClick(CompoundButton buttonView, boolean isChecked){
        if(isChecked){
            nextBtn.setEnabled(false);
            curBtn.setEnabled(true);
            lastBtn.setEnabled(true);
            lastBtn.setChecked(false);
            curBtn.setChecked(false);
            if(adapter != null)
                adapter.refresh(2);
            curState = 2;
        }
    }

    /**
     * 扫码
     * */
    @OnClick({R.id.qrBtn})
    public void OnQrBtnClick(){
//        HttpHeper.get().create(ExamService.class)
//                .getExamInfos("43",user.getName(), user.getIdCard(),user.getUserId())
//                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
//                .compose(getThread())
//                .subscribe(new BaseCallBack<ExamInfosEntity>(this) {
//                    @Override
//                    public void onCallBackSuccess(ExamInfosEntity data) {
//                        Gson json = new Gson();
//                        Intent intent = new Intent();
//                        intent.putExtra("ExamInfosEntity", json.toJson(data));
//                        intent.putExtra("ExamId", "43");
//                        intent.setClass(ExamLoadingActivity.this, ExamDoActivity.class);
//                        startActivity(intent);
//                    }
//
//                    @Override
//                    public void onFail(String mes) {
//                        showToast(mes);
//                    }
//                });

        new IntentIntegrator(this)
                .setCaptureActivity(QrCodeActivity.class)
                .setPrompt("请对准二维码")
                .setCameraId(0)
                .initiateScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() != null) {
                String url =  result.getContents();
                String examId =  analysisUrl(url,"homePage?examId=");
                if(examId == null){
                    examId =  analysisUrl(url,"html?examId=");
                    if(examId != null){
                        //签到
                        HttpHeper.get().create(ExamService.class).
                                checkUser(examId, user.getName(), user.getIdCard(),user.getCpId())
                                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                                .compose(getThread())
                                .subscribe(new BaseCallBack<Object>(this) {
                                    @Override
                                    public void onCallBackSuccess(Object result) {
                                        if(Integer.parseInt(result.toString()) == 200)showToast("",R.drawable.common_succes);
                                        else showToast("签到失败");
                                    }
                                    @Override
                                    public void onFail(String mes) {
                                        showToast(mes);
                                    }
                                });
                        return;
                       // examId = examId+"?0";
                    }
                    //签到
                }
                //考试
                if (TextUtils.isEmpty(examId)) showToast("请扫描正确的二维码");
                else {
                    //考试
                    String finalExamId = examId;
                    HttpHeper.get().create(ExamService.class)
                            .getExamInfos(examId,user.getName(), user.getIdCard(),user.getCpId())
                            .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                            .compose(getThread())
                            .subscribe(new BaseCallBack<ExamInfosEntity>(this) {
                                @Override
                                public void onCallBackSuccess(ExamInfosEntity data) {
                                    Gson json = new Gson();
                                    Intent intent = new Intent();
                                    intent.putExtra("ExamInfosEntity", json.toJson(data));
                                    intent.putExtra("ExamId", finalExamId);
                                    intent.putExtra("SaveQu", json.toJson(new ArrayList<ExamErrDetailEntity.SubjectBean >()) );
                                    intent.setClass(ExamLoadingActivity.this, ExamDoActivity.class);
                                    startActivity(intent);
                                }

                                @Override
                                public void onFail(String mes) {
                                    showToast(mes);
                                }
                            });
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 解析扫描得到的url，分解出examId
     * @param url
     */
    private String analysisUrl(String url, String path){
        String examId = null;
        String includeStr = path;
        if (url.contains(includeStr)){
            int first1=url.indexOf(includeStr);
            //从索引处到末尾（不包括索引处）
            String substr1=url.substring(first1);
            Log.d(TAG, ">>>substr1---" + substr1);
            int first2=substr1.indexOf("=");
            examId = substr1.substring(first2+1);
            Log.d(TAG, ">>>examId---" + examId);
        }
        return examId;
    }


    private boolean DoEffect(View view, MotionEvent event){
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                AnimationManager.Instance().DoScaleAction(view, 1.0f,1.05f,1.0f,1.05f,50);
                return false;
            case  MotionEvent.ACTION_UP:
                AnimationManager.Instance().DoScaleAction(view, 1.05f,1.0f,1.05f,1.0f,50);
                return true;
        }
        return false;
    }


}
